/*
 * @Description:
 * @Author: fhw
 * @Date: 2023-02-06 15:22:55
 */
import { FormConfig, FormUpload } from '@/components'
import { OssData } from '@/components/upload'
import UserImg from '@/components/user/userImg'
import { Resume, ResumeSkill, ResumeSkilltxt } from '@/interface/resume'
import { errorTips, successTips } from '@/utils'
import { isTrue } from '@/utils/tools'
import { List } from 'ant-design-vue'
import { RuleObject } from 'ant-design-vue/lib/form/interface'
import { clone, isEmpty, map } from 'ramda'
import { defineComponent, ref } from 'vue'
import { isTableEmpty } from '@/utils'
import './style.scss'
const emailreg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
function emailValidator(rule: RuleObject, value: string) {
	if (!new RegExp(emailreg).test(value)) {
		return Promise.reject('请输入正确的邮箱地址')
	}
	return Promise.resolve()
}
const rules = {
	name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	sex: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	nativePlace: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	message: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	sendEmail: [{ required: true, trigger: 'blur', validator: emailValidator }],
	mail: [{ required: true, trigger: 'blur', validator: emailValidator }],
	education: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	phone: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	experience: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	occupation: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	title: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	count: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
}
export default defineComponent({
	name: 'SettingsResume',
	setup() {
		const userId = localStorage.getItem('userId') as string
		const antdForm = ref<AntdFrom>()
		const resumeSkill: ResumeSkill[] = [{ count: 0 }, { count: 0 }, { count: 0 }]
		const resumeSkilltxt: ResumeSkilltxt[] = [{}, {}, {}, {}, {}]
		const pageState = ref({
			loading: false,
			data: {
				resumeSkill: clone(resumeSkill),
				resumeSkilltxt: [{}, {}, {}, {}, {}],
				resumeExperience: [{}],
				resumeProject: [
					{
						technology: [{ text: '' }],
					},
				],
				resumeEducation: [
					{
						title: '',
						major: '',
						date: '',
					},
				],
			} as Resume,
		})
		getResume()
		/** 获取简历信息 */
		async function getResume() {
			pageState.value.loading = true
			const { success, data } = await API.blog.resume.getResumeInfo.request(userId)
			pageState.value.loading = false
			if (success && data) {
				pageState.value.data = clone(data)
				const skilltxtNum = pageState.value.data.resumeSkilltxt?.length ?? resumeSkilltxt.length
				const skillNum = pageState.value.data.resumeSkill?.length ?? resumeSkill.length
				if (!isTrue(data.resumeSkill)) {
					pageState.value.data.resumeSkill = clone(resumeSkill)
				}
				if (!isTrue(data.resumeSkilltxt)) {
					pageState.value.data.resumeSkilltxt = clone(resumeSkilltxt)
				}
				/** 技能列表不满足数量则进行补充 */
				for (let index = skilltxtNum; index < resumeSkilltxt.length; index++) {
					pageState.value.data.resumeSkilltxt?.push(clone(resumeSkilltxt[0]))
				}
				for (let index = skillNum; index < resumeSkill.length; index++) {
					pageState.value.data.resumeSkill?.push(clone(resumeSkill[0]))
				}
			}
		}
		/** 头像上传 */
		async function handleChange(data: OssData) {
			if (!data.url) {
				errorTips('上传失败，请联系管理员处理')
				return
			}
			pageState.value.data.userImage = data.url
		}
		/** 更新简历个人信息 */
		async function updateUserResume() {
			const ok = await antdForm.value?.validate().then(
				() => null,
				() => true
			)
			if (ok) {
				return
			}
			const params = {
				userId,
				PDFUrl: pageState.value.data.PDFUrl,
				education: pageState.value.data.education,
				experience: pageState.value.data.experience,
				mail: pageState.value.data.mail,
				name: pageState.value.data.name,
				nativePlace: pageState.value.data.nativePlace,
				occupation: pageState.value.data.occupation,
				sex: pageState.value.data.sex,
				phone: pageState.value.data.phone,
			}
			pageState.value.loading = true
			const { success } = await API.blog.resume.updateUserResume.request(params)
			pageState.value.loading = false
			if (success) {
				successTips('更新个人资料成功')
			}
		}
		/** 更新技能信息 */
		async function updateSkillText() {
			const isTitle = pageState.value.data.resumeSkill?.some((item) => !isTrue(item.title))
			if (isTitle) {
				errorTips('请输入掌握的技能标题')
				return
			}
			pageState.value.loading = true
			const { success } = await API.blog.resume.updateSkill.request({
				resumeId: pageState.value.data.id,
				resumeSkill: pageState.value.data.resumeSkill,
				userId,
			})
			const { success: skillTextSuccess } = await API.blog.resume.updateSkillText.request({
				resumeId: pageState.value.data.id,
				resumeSkilltxt: pageState.value.data.resumeSkilltxt?.filter((item) => isTrue(item.text)),
				userId,
			})
			pageState.value.loading = false
			getResume()
			if (success && skillTextSuccess) {
				successTips('更新技能列表成功')
			}
		}
		const filterWorkKey = [
			{
				value: 'title',
				label: '公司名称',
			},
			{
				value: 'date',
				label: '工作时间',
			},
			{
				value: 'text',
				label: '公司介绍',
			},
		]
		/** 更新工作经验 */
		async function updateExperience() {
			const empty = isTableEmpty(pageState.value.data.resumeExperience ?? [], filterWorkKey)
			if (!isEmpty(empty)) {
				errorTips(`${empty}为空`)
				return
			}
			pageState.value.loading = true
			const { success } = await API.blog.resume.updateExperience.request({
				userId: userId,
				resumeId: pageState.value.data.id,
				resumeExperience: pageState.value.data?.resumeExperience,
			})
			pageState.value.loading = false
			if (success) {
				successTips('更新成功')
				getResume()
			}
		}
		const filterProjectKey = [
			{
				value: 'title',
				label: '项目名称',
			},
			{
				value: 'describe',
				label: '项目描述',
			},
			{
				value: 'technology',
				label: '项目职责',
			},
		]
		/** 更新项目项目经验 */
		async function updateProject() {
			const empty = isTableEmpty(pageState.value.data.resumeProject ?? [], filterProjectKey)
			if (!isEmpty(empty)) {
				errorTips(`${empty}为空`)
				return
			}
			pageState.value.loading = true

			const { success } = await API.blog.resume.updateProject.request({
				resumeProject: pageState.value.data?.resumeProject,
				userId: userId,
				resumeId: pageState.value.data?.id,
			})
			pageState.value.loading = false
			if (success) {
				successTips('更新成功')
				getResume()
			}
		}
		const filterPducationKey = [
			{
				value: 'title',
				label: '学校名称',
			},
			{
				value: 'date',
				label: '就读时间',
			},
			{
				value: 'major',
				label: '专业',
			},
		]
		async function updateEducation() {
			const empty = isTableEmpty(pageState.value.data?.resumeEducation ?? [], filterPducationKey)
			if (!isEmpty(empty)) {
				errorTips(`${empty}为空`)
				return
			}
			pageState.value.loading = true
			const { success } = await API.blog.resume.updateEducation.request({
				resumeEducation: pageState.value.data.resumeEducation,
				userId: userId,
				resumeId: pageState.value.data.id,
			})
			pageState.value.loading = false
			if (success) {
				successTips('更新成功')
				getResume()
			}
		}
		return () => (
			<div id="settings-resume">
				<div class="settings-resume-menu">
					<a-anchor getContainer={() => document.querySelector('#settings-resume')} showInkInFixed offsetTop={20}>
						<a-anchor-link href="#settings-resume-home" title="个人信息" />
						<a-anchor-link />
						<a-anchor-link href="#settings-resume-skills" title="技能" />
						<a-anchor-link />
						<a-anchor-link href="#settings-resume-work" title="工作" />
						<a-anchor-link />
						<a-anchor-link href="#settings-resume-project" title="项目" />
						<a-anchor-link />
						<a-anchor-link href="#settings-resume-education" title="教育" />
					</a-anchor>
				</div>
				<div class="conWidth">
					<a-divider id="settings-resume-home">
						<h4>个人信息</h4>
					</a-divider>
					<div class="resume-home">
						<div>
							<FormUpload
								onChange={handleChange}
								v-slots={{
									text: () => (
										<UserImg
											key="resume-userImg"
											iconSize={166}
											imgSize={166}
											headimgurl={pageState.value.data?.userImage}
										/>
									),
								}}
							></FormUpload>
						</div>
						<a-form
							class="resume-ant-form"
							model={pageState.value.data}
							labelCol={{ span: 8 }}
							wrapperCol={{ span: 16 }}
							rules={rules}
							ref={antdForm}
						>
							<a-row>
								<a-col span={12}>
									<a-form-item name="name" label="姓名">
										<a-input v-model={[pageState.value.data.name, 'value']} placeholder="请输入姓名" />
									</a-form-item>
								</a-col>
								<a-col span={12}>
									<a-form-item name="sex" label="性别">
										<FormConfig v-model={[pageState.value.data.sex, 'value']} placeholder="请输入性别" prop="sex" />
									</a-form-item>
								</a-col>
								<a-col span={12}>
									<a-form-item name="nativePlace" label="籍贯">
										<a-input v-model={[pageState.value.data.nativePlace, 'value']} placeholder="请输入籍贯" />
									</a-form-item>
								</a-col>
								<a-col span={12}>
									<a-form-item name="mail" label="邮箱">
										<a-input v-model={[pageState.value.data.mail, 'value']} placeholder="请输入邮箱" />
									</a-form-item>
								</a-col>
								<a-col span={12}>
									<a-form-item name="education" label="学历">
										<a-input v-model={[pageState.value.data.education, 'value']} placeholder="请输入学历" />
									</a-form-item>
								</a-col>
								<a-col span={12}>
									<a-form-item name="phone" label="电话">
										<a-input v-model={[pageState.value.data.phone, 'value']} placeholder="请输入电话" />
									</a-form-item>
								</a-col>
								<a-col span={12}>
									<a-form-item name="experience" label="工作经验">
										<a-input v-model={[pageState.value.data.experience, 'value']} placeholder="请输入工作经验" />
									</a-form-item>
								</a-col>
								<a-col span={12}>
									<a-form-item name="occupation" label="职业">
										<a-input v-model={[pageState.value.data.occupation, 'value']} placeholder="请输入职业" />
									</a-form-item>
								</a-col>
								<a-col span={12}>
									<a-form-item name="PDFUrl" label="简历地址">
										<a-textarea
											rows={4}
											v-model={[pageState.value.data.PDFUrl, 'value']}
											placeholder="请输入简历地址"
										/>
									</a-form-item>
								</a-col>
								<a-col span={24} style="text-align: center;">
									<a-button type="primary" onClick={updateUserResume} loading={pageState.value.loading}>
										保存信息
									</a-button>
								</a-col>
							</a-row>
						</a-form>
					</div>
					<a-row id="settings-resume-skills">
						<a-col span={10}>
							<a-divider>
								<h4>掌握的技能</h4>
							</a-divider>
							<a-row class="resume-skills">
								{map((item) => {
									return (
										<a-col span={24}>
											<div class="skill-block">
												<div class="skill-block-inner">
													<div class="skill-title">
														<a-input v-model={[item.title, 'value']} placeholder="请输入标题" />
													</div>
													<a-slider v-model={[item.count, 'value']} />
												</div>
											</div>
										</a-col>
									)
								}, pageState.value.data?.resumeSkill ?? [])}
							</a-row>
						</a-col>
						<a-col span={14}>
							<a-divider>
								<h4>专业技能</h4>
							</a-divider>
							<a-list
								size="large"
								bordered
								dataSource={pageState.value.data.resumeSkilltxt}
								renderItem={({ index }: any) => {
									return (
										<List.Item>
											<a-input
												v-model={[(pageState.value.data.resumeSkilltxt as ResumeSkilltxt[])[index].text, 'value']}
											/>
										</List.Item>
									)
								}}
							/>
						</a-col>
						<a-col span={24} style="text-align: center;margin:20px 0">
							<a-button type="primary" onClick={updateSkillText} loading={pageState.value.loading}>
								保存技能信息
							</a-button>
						</a-col>
					</a-row>
					<a-divider id="settings-resume-work">
						<h4>工作经验</h4>
					</a-divider>
					<a-row class="resume-work">
						<div class="edit">
							<a-button
								loading={pageState.value.loading}
								type="primary"
								onClick={() => {
									pageState.value.data.resumeExperience?.push({})
								}}
							>
								添加工作
							</a-button>
						</div>
						{pageState.value.data?.resumeExperience?.map((item, index) => {
							return (
								<a-col span={12} key={`resume-work-${index}`}>
									<div class="inner-box">
										<a-form
											class="work-form"
											model={pageState.value.data}
											labelCol={{ span: 5 }}
											wrapperCol={{ span: 19 }}
											ref={antdForm}
										>
											<a-form-item name="date" label="时间">
												<a-input v-model={[item.date, 'value']} placeholder="请输入时间" />
											</a-form-item>
											<a-form-item name="title" label="公司名称">
												<a-input v-model={[item.title, 'value']} placeholder="请输入公司名称" />
											</a-form-item>
											<a-form-item name="text" label="公司介绍">
												<a-textarea rows={4} v-model={[item.text, 'value']} placeholder="请输入公司介绍" />
											</a-form-item>
											<a-form-item style="text-align: right;" labelCol={{ span: 0 }} wrapperCol={{ span: 24 }}>
												<a-button
													type="primary"
													danger
													onClick={() => {
														pageState.value.data?.resumeExperience?.splice(index, 1)
													}}
												>
													删除工作
												</a-button>
											</a-form-item>
										</a-form>
									</div>
								</a-col>
							)
						})}
					</a-row>
					{(pageState.value.data?.resumeExperience?.length ?? 0) > 0 && (
						<div style="text-align: center;margin:20px auto;">
							<a-button type="primary" onClick={updateExperience} loading={pageState.value.loading}>
								保存工作信息
							</a-button>
						</div>
					)}
					<a-divider id="settings-resume-project">
						<h4>项目经验</h4>
					</a-divider>
					<div class="resume-project">
						<div class="edit">
							<a-button
								loading={pageState.value.loading}
								type="primary"
								onClick={() => {
									pageState.value.data.resumeProject?.push({ technology: [{ text: '' }] })
								}}
							>
								添加项目
							</a-button>
						</div>
						{pageState.value.data.resumeProject?.map((item, index) => {
							return (
								<a-form
									class="resume-work-ant-form"
									model={pageState}
									labelCol={{ span: 3 }}
									wrapperCol={{ span: 12 }}
									ref={antdForm}
								>
									<div class="project-box">
										<div class="edit">
											<a-button
												type="primary"
												danger
												onClick={() => {
													pageState.value.data.resumeProject?.splice(index, 1)
												}}
											>
												删除项目
											</a-button>
										</div>
										<a-form-item name="title" label="项目名称">
											<a-input v-model={[item.title, 'value']} placeholder="请输入项目名称" />
										</a-form-item>

										<a-form-item name="describe" label="项目简介">
											<a-textarea rows={4} v-model={[item.describe, 'value']} placeholder="请输入项目简介" />
										</a-form-item>
										<a-divider>
											<h5>项目职责</h5>
										</a-divider>
										<div class="technology">
											<div class="edit">
												<a-button
													type="primary"
													onClick={() => {
														item.technology?.push({ text: '' })
													}}
												>
													添加项目职责
												</a-button>
											</div>

											<ul>
												{item.technology?.map((data, index) => (
													<li>
														<div style="display: flex;">
															<a-input
																style={{ width: '86%', marginRight: '10px' }}
																v-model={[data.text, 'value']}
																placeholder="请输入项目职责"
															/>
															<a-button
																type="primary"
																danger
																onClick={() => {
																	item.technology?.splice(index, 1)
																}}
															>
																删除
															</a-button>
														</div>
													</li>
												))}
											</ul>
										</div>
										<a-divider />
									</div>
								</a-form>
							)
						})}
						{(pageState.value.data?.resumeProject?.length ?? 0) > 0 && (
							<div style="text-align: center;margin:20px auto;">
								<a-button type="primary" onClick={updateProject} loading={pageState.value.loading}>
									保存项目信息
								</a-button>
							</div>
						)}
					</div>
					<a-divider id="settings-resume-education">
						<h4>教育经历</h4>
					</a-divider>
					<div class="resume-education">
						<div class="edit">
							<a-button
								loading={pageState.value.loading}
								type="primary"
								onClick={() => {
									pageState.value.data.resumeEducation?.push({
										title: '',
										major: '',
										date: '',
									})
								}}
							>
								添加教育经历
							</a-button>
						</div>

						{pageState.value.data.resumeEducation?.map((item, index) => {
							return (
								<a-form
									model={pageState.value.data.resumeEducation}
									labelCol={{ span: 6 }}
									wrapperCol={{ span: 12 }}
									class="resume-education-form"
								>
									<a-row>
										<a-col span={24}>
											<a-form-item name="title" label="学校" labelCol={{ span: 3 }}>
												<a-input v-model={[item.title, 'value']} placeholder="请输入学校" />
											</a-form-item>
										</a-col>
										<a-col span={11}>
											<a-form-item name="major" label="专业">
												<a-input v-model={[item.major, 'value']} placeholder="请输入专业" />
											</a-form-item>
										</a-col>
										<a-col span={11}>
											<a-form-item name="date" label="就读时间">
												<a-input v-model={[item.date, 'value']} placeholder="请输入就读时间" />
											</a-form-item>
										</a-col>
										<a-col span={2}>
											<a-button
												type="primary"
												danger
												onClick={() => {
													pageState.value.data.resumeEducation?.splice(index, 1)
												}}
											>
												删除经历
											</a-button>
										</a-col>
									</a-row>
									<a-divider></a-divider>
								</a-form>
							)
						})}
						{(pageState.value.data?.resumeEducation?.length ?? 0) > 0 && (
							<div style="text-align: center;margin:20px auto;">
								<a-button type="primary" onClick={updateEducation} loading={pageState.value.loading}>
									保存教育经历信息
								</a-button>
							</div>
						)}
					</div>
				</div>
			</div>
		)
	},
})
